package cn.wenlihelp.service.impl;

import cn.wenlihelp.bean.Account;
import cn.wenlihelp.mapper.AccountMapper;
import cn.wenlihelp.service.AccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;

    @Override
    public PageInfo<Account> findAll(int page, int limit, Account account) {
        PageHelper.startPage(page, limit);
        List<Account> accounts = accountMapper.findAll(account);
        return new PageInfo<>(accounts);
    }

    @Override
    public Account findById(Long id) {
        return accountMapper.selectByPrimaryKey(id);
    }

    @Override
    public Account findByUserNameAndPassword(String userName, String userPassword) {
        return accountMapper.findByUserNameAndPassword(userName,userPassword);
    }

    @Override
    public boolean deleteByIds(Integer[] ids) {
        try {
            accountMapper.deleteByIds(ids);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean insert(Account account) {
        try {
            return accountMapper.insertSelective(account) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateByPrimaryKey(Account account) {
        try {
            return accountMapper.updateByPrimaryKeySelective(account) > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    @Transactional
    @Override
    public void roleMapping(Integer accountId, Integer[] roleIds) {
        //1.删除原有关联信息
        this.accountMapper.deleteAccountRoleMapping(accountId);
        //2.新增新的关联信息

        if(roleIds != null && roleIds.length > 0 ) {
            this.accountMapper.addRoleMapping(accountId,roleIds);
        }
    }
}
